package cn.nsu.douban.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.nsu.douban.dao.dao.IUserDao;
import cn.nsu.douban.entity.User;
import cn.nsu.douban.exception.MyAppException;

@Repository
@SuppressWarnings("all")
public class IUserDaoImpl extends HibernateDaoSupport implements IUserDao {
   
	@Resource
	public void setSesssionFactry(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	public User loginByloginNameAndPasswod(String loginName, String password) {
                       
		String queryString = "from User where loginname=? and password=?";
		List<User> userList = this.getHibernateTemplate().find(queryString,loginName,password);
		if (userList != null && userList.size() > 0) {
			return userList.get(0);
		}
		return null;
	}
   
	public Integer findUsername(String loginname) {
		DetachedCriteria detachedCriteria=DetachedCriteria.forClass(User.class);
		detachedCriteria.setProjection(Projections.rowCount());
		detachedCriteria.add(Restrictions.eq("loginname", loginname));
		List<Long> count = this.getHibernateTemplate().findByCriteria(detachedCriteria);
		return count.get(0).intValue();
	}

	@Override
	public void save(User user)  throws MyAppException{
		try {
			this.getHibernateTemplate().save(user);
		} catch (Exception e) {
               throw new MyAppException("注册出错 :");
		}
	}

}
